package com.hw.shortlink.admin.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.hw.shortlink.admin.common.biz.user.UserContext;
import com.hw.shortlink.admin.common.biz.user.UserInfoDTO;
import com.hw.shortlink.admin.common.constant.RedisCacheConstants;
import com.hw.shortlink.admin.common.convention.exception.ClientException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import static com.hw.shortlink.admin.common.enums.UserErrorCodeEnum.USER_NOT_LOGIN;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        String requestURI = request.getRequestURI();

        //为用户注册放行，springMvcConfig哪里设置排除路径不能指定请求方法
        if (requestURI.equals("/api/short-link/admin/v1/user") && method.equals("POST")) {
            return true; // 放行
        }
        String token = request.getHeader("token");
        String username = request.getHeader("username");
//        if(token==null||username==null ){
//            throw new ClientException(USER_NOT_LOGIN);
//        }
        if(!StrUtil.isAllNotBlank(username,token)){
            throw new ClientException(USER_NOT_LOGIN);
        }
        Object userInfoJson = stringRedisTemplate
                .opsForHash()
                .get(RedisCacheConstants.USER_LOGIN_KEY + username,token);


        if(userInfoJson==null){
            throw new ClientException(USER_NOT_LOGIN);
        }
        UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJson.toString(), UserInfoDTO.class);

        userInfoDTO.setToken(token);

        UserContext.setUser(userInfoDTO);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        UserContext.removeUser();
    }
}
